import React, { useEffect, useRef, useState } from 'react'
import { Group, Layer, Line, Rect, Stage, Transformer } from 'react-konva'

const DraggableGroupExample: React.FC = () => {
  const groupRef = useRef<any>(null)
  const transformerRef = useRef<any>(null)
  const [rectSize, setRectSize] = useState({ width: 200, height: 100 })

  // 计算 Group 的边界
  const calculateBounds = () => {
    if (groupRef.current) {
      const box = groupRef.current.getClientRect() // 获取 Group 的边界
      setRectSize({ width: box.width, height: box.height })
    }
  }

  // 绑定 Transformer 到 Group
  useEffect(() => {
    if (transformerRef.current && groupRef.current) {
      transformerRef.current.nodes([groupRef.current])
      transformerRef.current.getLayer().batchDraw()
    }
  }, [])

  return (
    <Stage width={window.innerWidth} height={window.innerHeight}>
      <Layer>
        {/* 可拖拽和变换的 Group */}
        <Group
          ref={groupRef}
          draggable
          onDragEnd={calculateBounds} // 拖拽结束时重新计算边界
          onTransformStart={() => {
            setRectSize({ width: 0, height: 0 })
          }}
          onTransformEnd={e => {
            const node = e.target
            const { width, height } = node.getClientRect()
            console.log('🚀 ~ width, height:', width, height)

            setRectSize({ width, height })
          }} // 变换时重新计算边界
        >
          {/* 动态调整矩形大小 */}
          <Rect width={rectSize.width} x={0} y={0} height={rectSize.height} fill='black' opacity={0.1} />
          {/* 第一条线 */}
          <Line points={[0, 0, 100, 100]} stroke='red' strokeWidth={3} />
          {/* 第二条线 */}
          <Line points={[100, 100, 200, 0]} stroke='blue' strokeWidth={3} />
          {/* 第三条线 */}
          <Line points={[200, 0, 0, 0]} stroke='green' strokeWidth={3} />
        </Group>

        {/* Transformer 组件 */}
        <Transformer
          ref={transformerRef}
          boundBoxFunc={(oldBox, newBox) => {
            // 限制最小缩放比例
            if (newBox.width < 50 || newBox.height < 50) {
              return oldBox
            }
            return newBox
          }}
        />
      </Layer>
    </Stage>
  )
}

export default DraggableGroupExample
